﻿using System;
using System.Collections;
using Eneta.Portal.Common;
using Microsoft.SharePoint;

namespace Eneta.Portal.Authentication.Live
{
    public class BlogUserProfile
    {
        protected string strId;
        protected string strPicture;
        protected string strDepartment;
        protected string strJobTitle;
        protected string strSipAddress;
        protected DateTime dateCreated;
        protected DateTime dateLastLogin;
        protected DateTime dateLockedOn;

        static protected object cache;

        public string DisplayName { get; set; }
        public string Email { get; set; }
        public int ItemId { get; internal set; }

        public string Id
        {
            get
            {
                return strId;
            }
        }

        public string AboutMe { get; set; }

        public string Picture
        {
            get
            {
                return strPicture;
            }
            set
            {
                if (Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute))
                {
                    strPicture = value;
                }
            }
        }

        public string Department
        {
            get
            {
                return strDepartment;
            }
            set
            {
                strDepartment = value;
            }
        }

        public string JobTitle
        {
            get
            {
                return strJobTitle;
            }
            set
            {
                strJobTitle = value;
            }
        }

        public string SipAddress
        {
            get
            {
                return strSipAddress;
            }
            set
            {
                strSipAddress = value;
            }
        }

        public bool Approved { get; set; }
        public bool Locked { get; set; }

        public DateTime Created
        {
            get
            {
                return dateCreated;
            }
        }

        public DateTime LastLogin
        {
            get
            {
                return dateLastLogin;
            }
            set
            {
                dateLastLogin = value;
            }
        }

        public DateTime LockedOn
        {
            get
            {
                return dateLockedOn;
            }
            set
            {
                dateLockedOn = value;
            }
        }

        public BlogUserProfile(SPListItem user)
        {
            //strId = GetListItemString(_user, "Title");
            strId = GetListItemString(user, "SysID");
            //strDisplayName = GetListItemString(_user, "DisplayName");
            DisplayName = GetListItemString(user, "Title");
            strDepartment = GetListItemString(user, "Department");
            Email = GetListItemString(user, "EMail");
            AboutMe = GetListItemString(user, "AboutMe");
            strPicture = GetListItemString(user, "Picture");
            strJobTitle = GetListItemString(user, "JobTitle");
            strSipAddress = GetListItemString(user, "SipAddress");
            ItemId = user.ID;
            Locked = GetListItemBool(user, "Locked");
            Approved = true;

            dateCreated = DateTime.Now;
            dateLastLogin = DateTime.Now;
            dateLockedOn = DateTime.MaxValue;
        }

        static public BlogUserProfile GetUser(string id)
        {
            BlogUserProfile ret = null;

            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    using (var elevSite = new SPSite(AuthConfig.ProfileSiteUrl))
                    {
                        using (var elevWeb = elevSite.OpenWeb())
                        {
                            var list = elevWeb.Lists[AuthConfig.ProfileList];
                            var q = new SPQuery();
                            if (id.IndexOf("@") != -1)
                            {
                                q.Query = string.Format("<Where><Eq><FieldRef Name='Email'/><Value Type='Text'>{0}</Value></Eq></Where>", id);
                            }
                            else
                            {
                                q.Query = string.Format("<Where><Eq><FieldRef Name='SysID'/><Value Type='Text'>{0}</Value></Eq></Where>", id);
                            }
                            var items = list.GetItems(q);
                            if (items.Count != 0)
                            {
                                //                                cache = new BlogUserProfile(items[0]);
                                ret = new BlogUserProfile(items[0]);
                            }
                        }
                    }
                }
            );

            /*if (cache != null)
            {
                ret = (BlogUserProfile)cache;
                cache = null;
            }*/

            return ret;
        }

        static public BlogUserProfile[] GetUsersByTag(string id, string tag)
        {
            ArrayList ret = null;

            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    var array = new ArrayList();
                    using (var elevSite = new SPSite(AuthConfig.ProfileSiteUrl))
                    {
                        using (var elevWeb = elevSite.OpenWeb())
                        {
                            var list = elevWeb.Lists[AuthConfig.ProfileList];
                            var q = new SPQuery();
                            q.Query = string.Format("<Where><Contains><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Contains></Where>", tag, id);
                            var items = list.GetItems(q);
                            if (items.Count != 0)
                            {
                                foreach (SPListItem item in items)
                                {
                                    array.Add(new BlogUserProfile(item));
                                }
                            }
                        }
                    }
                    //cache = array;
                    ret = array;
                }
            );

            //if (cache != null)
            //{
            //    ret = (ArrayList)cache;
            //    cache = null;
            //}

            return (BlogUserProfile[])ret.ToArray(typeof(BlogUserProfile));
        }

        static public BlogUserProfile[] GetAllUsers()
        {
            ArrayList ret = null;

            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    var array = new ArrayList();
                    using (var elevSite = new SPSite(AuthConfig.ProfileSiteUrl))
                    {
                        using (var elevWeb = elevSite.OpenWeb())
                        {
                            var list = elevWeb.Lists[AuthConfig.ProfileList];
                            if (list.Items.Count != 0)
                            {
                                foreach (SPListItem item in list.Items)
                                {
                                    array.Add(new BlogUserProfile(item));
                                }
                            }
                        }
                    }
                    //cache = array;
                    ret = array;
                }
            );

            //if (cache != null)
            //{
            //    ret = (ArrayList)cache;
            //    cache = null;
            //}

            return (BlogUserProfile[])ret.ToArray(typeof(BlogUserProfile));
        }
        //C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
        static public bool CreateUser(string id, string email)
        {
            var ret = false;

            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    using (var elevSite = new SPSite(AuthConfig.ProfileSiteUrl))
                    {
                        using (var elevWeb = elevSite.OpenWeb())
                        {
                            elevSite.AllowUnsafeUpdates = true;
                            elevWeb.AllowUnsafeUpdates = true;
                            var list = elevWeb.Lists[AuthConfig.ProfileList];
                            var q = new SPQuery();
                            q.Query = string.Format("<Where><Eq><FieldRef Name='SysID'/><Value Type='Text'>{0}</Value></Eq></Where>", id);
                            var items = list.GetItems(q);
                            if (items.Count == 0)
                            {
                                var item = list.Items.Add();
                                item["EMail"] = email;
                                item["SysID"] = id;
                                item.Update();
                                //cache = true;
                            }
                        }
                    }
                }
            );

            //if (cache != null)
            //{
            //    ret = (bool)cache;
            //    cache = null;
            //}

            return ret;
        }

        public void PushProfile()
        {
            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    using (SPSite elevSite = new SPSite(AuthConfig.ProfileSiteUrl))
                    {
                        using (SPWeb elevWeb = elevSite.OpenWeb())
                        {
                            foreach (SPListItem item in elevWeb.Lists["LiveProfileSync"].Items)
                            {
                                using (SPSite site = new SPSite(item["Url"].ToString()))
                                {
                                    using (SPWeb sweb = site.OpenWeb())
                                    {
                                        site.AllowUnsafeUpdates = true;
                                        sweb.AllowUnsafeUpdates = true;
                                        SPList list = sweb.Lists["User Information List"];
                                        SPQuery query = new SPQuery();
                                        query.Query = string.Format("<Where><Contains><FieldRef Name='Name'/><Value Type='Text'>{0}</Value></Contains></Where>", Id);
                                        SPListItemCollection items = list.GetItems(query);

                                        if (items.Count > 0)
                                        {
                                            SPListItem uItem = items[0];
                                            uItem[uItem.Fields.GetFieldByInternalName("Title").Title] = DisplayName;
                                            uItem["EMail"] = Email;
                                            uItem["Notes"] = AboutMe;
                                            uItem["Picture"] = Picture;
                                            uItem["Department"] = Department;
                                            uItem["JobTitle"] = JobTitle;
                                            uItem["SipAddress"] = SipAddress;
                                            uItem.Update();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            );
        }

        public void Update()
        {
            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    using (var elevSite = new SPSite(AuthConfig.ProfileSiteUrl))
                    {
                        using (var elevWeb = elevSite.OpenWeb())
                        {
                            elevSite.AllowUnsafeUpdates = true;
                            elevWeb.AllowUnsafeUpdates = true;
                            var list = elevWeb.Lists[AuthConfig.ProfileList];
                            var q = new SPQuery();
                            q.Query = string.Format("<Where><Eq><FieldRef Name='SysID'/><Value Type='Text'>{0}</Value></Eq></Where>", Id);
                            var items = list.GetItems(q);
                            if (items.Count != 0)
                            {
                                var item = items[0];
                                try
                                {
                                    item["Email"] = Email;
                                }
                                catch
                                { }
                                try
                                {
                                    item[item.Fields.GetFieldByInternalName("Title").Title] = DisplayName;
                                    item["DisplayName"] = DisplayName;
                                }
                                catch
                                { }
                                try
                                {
                                    item["Department"] = Department;
                                }
                                catch
                                { }
                                try
                                {
                                    item["AboutMe"] = AboutMe;
                                }
                                catch
                                { }
                                try
                                {
                                    item["Picture"] = Picture;
                                }
                                catch
                                { }
                                try
                                {
                                    item["JobTitle"] = JobTitle;
                                }
                                catch
                                { }
                                try
                                {
                                    item["SipAddress"] = SipAddress;
                                }
                                catch
                                { }
                                item["ShowFirstName"] = true;
                                item["ShowLastName"] = true;
                                item["SendEventsInfo"] = true;
                                item["SendMSInfo"] = true;
                                item.Update();
                            }
                        }
                    }
                }
            );

        }

        private string GetListItemString(SPListItem item, string column)
        {
            var ret = "";
            var data = GetListItemData(item, column);

            if (data != null)
            {
                ret = data.ToString();
            }

            return ret;
        }

        private bool GetListItemBool(SPListItem item, string column)
        {
            bool ret = false;
            object data = GetListItemData(item, column);

            if (data != null)
            {
                ret = (bool)data;
            }

            return ret;
        }

        private object GetListItemData(SPListItem item, string column)
        {
            object ret;

            try
            {
                ret = item[column];
            }
            catch(Exception ex)
            {
                Logger.LogWarning("GetListItemData(): problem when accessing column " + column, GetType().ToString());
                Logger.LogException(ex);
                throw;
            }

            return ret;
        }
    }
}
